// 新风险等级配置
const RISK_LEVELS = {
  minute: 0.01,   // 1%
  hour: 0.025,    // 2.5%
  daily: 0.05     // 5%
};

// 事件监听
document.getElementById('accountSize').addEventListener('input', calculatePosition);
document.getElementById('stopLossPercent').addEventListener('input', calculatePosition);
document.getElementById('timeframe').addEventListener('change', calculatePosition);

function calculatePosition() {
  const account = parseFloat(document.getElementById('accountSize').value);
  const stopLossPercent = parseFloat(document.getElementById('stopLossPercent').value);
  const timeframe = document.getElementById('timeframe').value;

  if (!account || !stopLossPercent) return;

  const riskPercentage = RISK_LEVELS[timeframe];
  const positionSize = (account * riskPercentage) / (stopLossPercent / 100);
  const riskAmount = account * riskPercentage;

  document.getElementById('positionSize').textContent = positionSize.toFixed(2);
  document.getElementById('riskAmount').textContent = riskAmount.toFixed(2);
}

// 获取当前时间周期对应的风险等级
function getRiskLevel(timeframe) {
  const timeframeMap = {
    'D': RISK_LEVELS['1D'],
    'W': RISK_LEVELS['1D'],
    'M': RISK_LEVELS['1D'],
    '4H': RISK_LEVELS['4H'],
    '1H': RISK_LEVELS['30'],
    '30': RISK_LEVELS['30'],
    '15': RISK_LEVELS['LOWER'],
    '5': RISK_LEVELS['LOWER'],
    '1': RISK_LEVELS['LOWER']
  };
  return timeframeMap[timeframe] || RISK_LEVELS.LOWER;
}

// 加载保存的设置
function loadSettings() {
  chrome.storage.local.get(['account', 'stopLoss', 'timeframe'], (result) => {
    document.getElementById('accountSize').value = result.account || '';
    document.getElementById('stopLossPercent').value = result.stopLoss || '';
    document.getElementById('timeframe').value = result.timeframe || 'minute';
    calculatePosition();
  });
}

// 保存设置到本地
function saveSettings() {
  chrome.storage.local.set({
    account: document.getElementById('accountSize').value,
    stopLoss: document.getElementById('stopLossPercent').value,
    timeframe: document.getElementById('timeframe').value
  });
}

// 初始化时加载设置
document.addEventListener('DOMContentLoaded', loadSettings);

// 添加防抖函数
function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

// 修改保存监听
const debounceSave = debounce(saveSettings, 500);
document.getElementById('accountSize').addEventListener('input', () => {
  debounceSave();
  calculatePosition();
});
document.getElementById('stopLossPercent').addEventListener('input', () => {
  debounceSave();
  calculatePosition();
});
document.getElementById('timeframe').addEventListener('change', () => {
  debounceSave();
  calculatePosition();
}); 